<template>
  <div class="trend-page">
    <template v-if="data.length>0">
      <!-- 图表 -->
      <div class="left">
        <div class="date-box">
          <span class="tit">起止时间</span>
          <div class="search-time">
            <el-date-picker
              v-model="start"
              size="medium"
              type="date"
              placeholder="开始年"
              :clearable="false"
              :picker-options="pickerStart"
              class="elpicker"
              @change="changeStart">
            </el-date-picker>
            <span class="split">-</span>
            <el-date-picker
              v-model="end"
              size="medium"
              type="date"
              placeholder="结束年"
              :clearable="false"
              :picker-options="pickerEnd"
              class="elpicker"
              @change="changeEnd">
            </el-date-picker>
          </div>
          <span class="vbtn-toggle">
            <el-button type="primary" class="elbtn elbtn-left" :class="{'elbtn-active':tabChartActive===0}" @click="tabChartActive=0">
              <i class="iconfont icon-zhexiantu"></i>
            </el-button>
            <el-button type="primary" class="elbtn elbtn-right" :class="{'elbtn-active':tabChartActive===1}" @click="tabChartActive=1">
              <i class="iconfont icon-situation"></i>
            </el-button>
          </span>
        </div>
        <div style="position:relative;width:100%;height:400px;padding-bottom: 30px">
          <div id="chartAnalysisOne" :class="{'tab-active': tabChartActive===0}"></div>
          <div id="chartAnalysisTwo" :class="{'tab-active': tabChartActive===1}"></div>
        </div>
      </div>
      <!-- 列表 -->
      <div class="right">
        <h3>{{currentYear}}年</h3>
        <ul class="eltable">
          <li class="theader">
            <p class="w100">申请日</p>
            <p class="w100">公开日</p>
            <p>名称</p>
            <p class="w140">专利号</p>
          </li>
          <li v-for="(item, index) in listData" :key="index" class="tbody">
            <p class="w100">{{item.ad}}</p>
            <p class="w100">{{item.isd}}</p>
            <p :title="item.title">{{item.title}}</p>
            <p class="w140">{{item.pn}}</p>
          </li>
        </ul>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="ips"
          :current-page.sync="ipi"
          @current-change="getCurrentPage"
          class="elpagination">
        </el-pagination>
      </div>
    </template>
    <template v-else>
      <p class="empty-text">{{emptyText}}</p>
    </template>
  </div>
</template>

<script>
import axios from 'axios'
import Ecolors from '@/utils/chartsColors.js'
import {resize} from '@/utils/utils'
export default {
  mixins: [resize],
  props: {
    info: {
      type: Object
    },
  },
  data() {
    return {
      data: [],
      start: '',
      end: '',
      pickerStart: {
        disabledDate: (time) => {
          return this.disabledDate(time, this.end, 'gt')
        }
      },
      pickerEnd: {
        disabledDate: (time) => {
          return this.disabledDate(time, this.start, 'lt')
        }
      },
      tabChartActive: 0,
      chartAnalysisOne: '',
      chartAnalysisTwo: '',
      patentHeaderStyle: function(){
        return 'font-weight: 600; color: #241c75;'
      },
      patentCellStyle: function() {
        return 'color: #7674a3'
      },
      // 列表
      currentYear: '',
      listData: [],
      ipi: 1,
      ips: 6,
      total: 0,
      emptyText: '数据加载中...',
      cancel: null
    }
  },
  methods: {
    // 科研趋势分析
    getData() {
      let ths = this
      if (this.cancel) {
        this.cancel()
      }
      this.emptyText = '数据加载中...'
      let params = {
        musts: {
          date_sort: '1',
          'in2id.id': this.info.key,
        },
        aggs: {
          interval: 'YEAR',
          format: 'yyyy',
          field: 'ad',
          type: 'date'
        }
      }
      if (this.start !== '' && this.end !== '') {
        params['rangArr'] = [
          {
            start: this.start,
            end: this.end,
            field: 'ad'
          }
        ]
      }
      this.$post(this.$Url.team.analysis, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c
        })
      })
      .then(res => {
        let data = res.data || []
        this.data = data
        if (data && data.length > 0) {
          this.$nextTick(() => {
            if (!this.chartAnalysisOne && !this.chartAnalysisTwo) {
              this.chartAnalysisOne = this.$echarts.init(document.getElementById("chartAnalysisOne"))
              this.chartAnalysisTwo = this.$echarts.init(document.getElementById("chartAnalysisTwo"))

              this.chartAnalysisOne.on('click', (params) => {
                this.currentYear = params.name
                this.ipi = 1
                this.getListData()
              })
              this.chartAnalysisTwo.on('click', (params) => {
                this.currentYear = params.name
                this.ipi = 1
                this.getListData()
              })
            }

            let xData = []
            let sData = []
            data.forEach(v => {
              xData.push(v['key_as_string'])
              sData.push(v['doc_count'])
            })

            // 默认选中最新一年，如果为0则往前推
            if (data.length > 1) {
              for (let i=data.length-1;i>0;i--) {
                if (data[i] && data[i].doc_count !== 0) {
                  this.currentYear = data[i]['key_as_string']
                  break
                }
              }
            } else {
              this.currentYear = data[0]['key_as_string']
            }

            // 第一次展示时获取start和end时间范围
            if (this.start === '' && this.end === '') {
              let start = data[0]['key_as_string'] + '-01-01'
              let end = data[data.length-1]['key_as_string'] + '-12-31'
              this.start = start
              this.end = end
            }

            // 科研趋势分析列表
            this.getListData()
            
            this.renderChart(this.chartAnalysisOne, xData, sData, 'line')
            this.renderChart(this.chartAnalysisTwo, xData, sData, 'bar')
          })
          
        } else {
          this.emptyText = '暂无数据'
        }
      }).catch(err => {})
    },
    // 科研趋势分析列表
    getListData() {
      let start = this.currentYear + '-01-01'
      let end = this.currentYear + '-12-31'
      this.$post(this.$Url.team.search2, {
        musts: {
          date_sort: '1',
          'in2id.id': this.info.key
        },
        ipi: this.ipi,
        ips: this.ips,
        sort: [
          {
            isd: 'desc'
          }
        ],
        rangArr: [
          {
            field: 'ad',
            start,
            end
          }
        ]
      }).then(res => {
        this.listData = res.data.result
        this.total = res.data.page.totalRow || 0
      }).catch(err => {})
    },
    renderChart(chart, xData, sData, type) {
      let option = {
        tooltip: {
          confine: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000"
          },
          axisPointer: { type: "none" },
          formatter: function (params, ticket, callback) {
            var htmlStr = '';
            var valMap = {};
            for(var i=0;i<params.length;i++){
              var param = params[i];
              var xName = param.name;//x轴的名称
              var seriesName = param.seriesName;//图例名称
              var value = param.value;//y轴值
              var color = param.color;//图例颜色
              //过滤无效值
              if(value == '-'){
                  continue;
              }
              //过滤重叠值
              if(valMap[seriesName] == value){
                  continue;
              }
              if(i===0){
                htmlStr += xName + '<br/>';//x轴的名称
              }
              htmlStr +='<div>';
              //为了保证和原来的效果一样，这里自己实现了一个点的效果
              htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:'+color+';"></span>';
              //圆点后面显示的文本
              htmlStr += seriesName + '：' + value;
              htmlStr += '</div>';
              valMap[seriesName] = value;
            }
            return htmlStr;
          }
        },
        legend: {
          type: "scroll",
          data: ['专利数量'],
          bottom: 0,
          left: "5%",
          right: "5%"
        },
        grid: {
          bottom: 60
        },
        xAxis: {
          type: "category",
          boundaryGap: type === 'line' ? false : true,
          splitLine: {
            show: false,
            lineStyle: {
              color: "#f0f1f3"
            }
          },
          axisLine: {
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
          axisLabel: {
            textStyle: {
              color: "#9e9e9e"
            }
          },
          data: xData
        },
        yAxis: {
          type: "value",
          splitLine: {
            show: true,
            lineStyle: {
              color: "#f0f1f3"
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
          axisLabel: {
            textStyle: {
              color: "#9e9e9e"
            }
          }
        },
      }

      // 折线图
      if (type === 'line') {
        // 是否需要虚线
        let currentYear = Number(moment().format('YYYY'))
        let endYear = Math.max(...xData)
        let solid = []
        let dotted = []
        if (endYear >= currentYear) {
          xData.forEach((v, i) => {
            if (Number(v) < currentYear) {
              solid.push(sData[i])
              dotted.push('-')
            } else {
              solid.push('-')
              dotted.push(sData[i])
            }
          })
          dotted.forEach((v, i) => {
            if (v !== '-') {
              dotted[Number(i)-1] = sData[Number(i)-1]
            }
          })
        } else {
          xData.forEach((v, i) => {
            solid.push(sData[i])
          })
        }

        let series = [
          {
            name: '专利数量',
            type: "line",
            data: solid,
            symbol: "circle",
            symbolSize: 10,
            itemStyle: {
              borderWidth: 3,
              borderColor: '#fff',
              color: Ecolors.color[1]
            },
          },
        ]
        if (dotted.length > 0) {
          series.push({
            name: '专利数量', //虚线
            type: "line",
            data: dotted,
            symbol: "circle",
            symbolSize: 10,
            itemStyle: {
              borderWidth: 3,
              borderColor: '#fff',
              color: Ecolors.color[1],
            },
            lineStyle:{
              type:'dotted'  //'dotted'虚线 'solid'实线
            }
          })
        }

        option = {
          ...option,
          series
        }
      } else if (type === 'bar') { // 柱形图
        let solid = []
        xData.forEach((v, i) => {
          solid.push(sData[i])
        })
        let series = [
          {
            name: '专利数量',
            type,
            data: solid,
            barMaxWidth: 16,
            smooth: true,
            symbol: "circle",
            symbolSize: 10,
            itemStyle: {
              normal: {
                color: Ecolors.color[1]
              }
            },
            emphasis: {
              itemStyle: {
                opacity: '0.5'
              }
            },
          },
        ]

        option = {
          ...option,
          itemStyle: {
            barBorderRadius: [20, 20, 0, 0],
          },
          series
        }
      }

      chart.setOption(option, true)
    },
    disabledDate(time, d, type) {
      let md =  moment(d)
      if (type === 'gt') {
        if (time > md._d) {
          return true
        }
        return false
      } else if (type === 'lt') {
        if (time < md._d) {
          return true
        }
        return false
      }
    },
    changeStart(val) {
      this.start = moment(val).format('YYYY-MM-DD')
      this.getData()
    },
    changeEnd(val) {
      this.end = moment(val).format('YYYY-MM-DD')
      this.getData()
    },
    getCurrentPage(val) {
      this.ipi = val
      this.getListData()
    },
  },
  watch: {
    info(newVal, oldVal) {
      if (newVal.key !== oldVal.key) {
        this.getData()
      }
      // 展示最近10年
      // let end = moment().format('YYYY-MM-DD')
      // let arr = end.split('-')
      // let start = arr[0] - 10 + '-' + arr[1] + '-' + arr[2]
      // this.start = start
      // this.end = end
    }
  },
  mounted() {
    if (Object.keys(this.info).length > 0) {
      // 展示最近10年
      // let end = moment().format('YYYY-MM-DD')
      // let arr = end.split('-')
      // let start = arr[0] - 10 + '-' + arr[1] + '-' + arr[2]
      // this.start = start
      // this.end = end
      this.getData()
    }
  },
  beforeDestroy() {
    if (this.chartAnalysisOne) {
      this.chartAnalysisOne.dispose()
    }
    if (this.chartAnalysisTwo) {
      this.chartAnalysisTwo.dispose()
    }
    if (this.cancel) {
      this.cancel()
    }
  }
}
</script>

<style lang="scss" scoped>

.trend-page {
  position: relative;
  display: flex;
  .left {
    flex: .5;
    box-sizing: border-box;
    .date-box {
      position: relative;
      margin-top: 10px;
      .tit {
        display: inline-block;
        // width: 75px;
        margin-right: 10px;
        font-size: 14px;
        color: #2d3a86;
      }
      .search-time {
        display: inline-flex;
        align-items: center;
        .elpicker {
          width: 150px;
        }
        .split {
          display: inline-block;
          padding: 0 5px;
        }
      }
    }
    .vbtn-toggle {
      float: right;
      margin-right: 20px;
      .elbtn {
        width: 40px;
        height: 36px;
        padding: 0;
        border: 0;
        color: #b8b7ee;
        background-color: #e9e9fc;
        &.elbtn-left {
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
        &.elbtn-right {
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
          margin-left: 2px !important;
        }
        &.elbtn-active {
          color: #fff !important;
          background-color: $mainColor !important;
          &:hover, &:active {
            color: #fff;
            background-color: $mainColor !important;
          }
        }
      }
    }
    #chartAnalysisOne, #chartAnalysisTwo {
      position: absolute;
      top: 0;
      left: -9999px;
      width: 100%;
      height: 370px;
    }
    .tab-active {
      left: 0 !important;
    }
  }
  .right {
    flex: .5;
    float: none !important;
    min-width: 0;
    h3 {
      padding-bottom:12px;
      border-bottom:1px solid #b7b6eb;
      font-size: 14px;
      color: $mainColor;
    }
    .eltable {
      width: 100%;
      min-height: 280px;
      padding-left: 0;
      li {
        position: relative;
        display: flex;
        text-align: left;
        font-size: 14px;
        &.theader {
          line-height: 50px;
          color: $mainColor;
        }
        &.tbody {
          &:hover {
            p {
              font-weight: bold;
              color: $mainColor;
            }
            box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
          }
          p {
            line-height: 46px;
            color: #7d90ae;
          }
        }
        p {
          flex: 1;
          padding: 0 13px;
          margin-bottom: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          &.w100 {
            flex: initial;
            width: 124px;
          }
          &.w140 {
            flex: initial;
            width: 140px;
          }
        }
        
      }
    }
    .elpagination {
      margin-top: 30px;
      margin-bottom: 30px;
      text-align: right;
    }
  }
}
.empty-text {
  padding: 16px;
}
</style>